/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package CONTROLLERS;

//import static VIEW.CustomerUI.contactNumberEditInput;
import UTIL.DatabaseConnector;
import UTIL.InputValidator;
import VIEW.Main;
import VIEW.UserLogIn;
import VIEW.UserUI;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

/**
 *
 * @author AMD
 */
public class LogInController {
           private static UserLogIn userLogIn;
           private final DatabaseConnector dbConnector;
           private JTextField userNameInput;
           private JPasswordField passwordInput;
           private JCheckBox rememberMe;
           private JDialog forgotDialog;
           private JLabel questionLabel;
           private JTextField answerTextField;
           private JDialog setQuestionDialog;
           private JComboBox questions;
           private JTextField ansTextField;
           private boolean loggingIn = false;
           int attempts = 0;
           String name = "";
           String username = "";
           PreparedStatement selectStatement = null;
           public LogInController(JTextField userNameInput, JPasswordField passwordInput, JCheckBox rememberMe, 
                   UserLogIn userLogIn, JDialog forgotDialog, JLabel questionLabel, JTextField answerTextField,
                   JDialog setQuestionDialog, JComboBox questions, JTextField ansTextField){
               this.userNameInput = userNameInput;
               this.passwordInput = passwordInput;
               this.rememberMe = rememberMe;
               this.userLogIn = userLogIn;
               this.forgotDialog = forgotDialog;
               this.questionLabel = questionLabel;
               this.answerTextField = answerTextField;
               this.setQuestionDialog = setQuestionDialog;
               this.questions = questions;
               this.ansTextField = ansTextField;
               dbConnector= DatabaseConnector.getInstance();
           }

        public void userLogin(){
            if(!loggingIn){
                loggingIn = true;
            PreparedStatement selectStatement = null;
        try{
            
            ResultSet rs = dbConnector.query("SELECT username, password, name, type, question FROM users");
            String pas = new String(passwordInput.getPassword());
            boolean userNotFound = true;
            boolean isAdmin = false;
            boolean noQuestionSet = false;
            String un = userNameInput.getText();
            
            String type = "";
            String user = "";
            String pass = "";
            String question = "";
            while(rs.next()){
                user = rs.getString(1);
                pass = rs.getString(2);  
                //type = rs.getString(4);
                //question = rs.getString(5);
                //System.out.println(user);
                //System.out.println(pass);
                
                if(user.equals(un) && pass.equals(pas)){
                    userNotFound = false;
                    name = rs.getString(3);
                    type = rs.getString(4);
                    question = rs.getString(5);
                    System.out.println("Info: " + name + " has logged in.");
                    username = user;                    
                    break;
                    }else{
                    userNotFound = true;
                }
            }
            
                ResultSet res = dbConnector.query("SELECT type, question FROM users where username = '" + un + "'");
                res.next();
                
                type = res.getString("type");
                question = res.getString("question");
                
                if(type.equals("admin")){
                    isAdmin = true;                    
                }else{
                    isAdmin = false;
                }
                res.close();
                if(isAdmin && question.equals("N/A")){
                    noQuestionSet = true;
                }else{
                    noQuestionSet = false;
                }
                
            if(userNotFound){
                attempts++;
                
                if(attempts < 5){
                JOptionPane.showMessageDialog(null, "The username or password you entered is incorrect.", "Incorrect username / password",JOptionPane.ERROR_MESSAGE);
                }else if(!isAdmin && attempts >= 5){
                    System.out.println("Info: " + name + " has incurred 5 incorrect attempts.");
                JOptionPane.showMessageDialog(null, "If you forgot your password please contact the admin.", "Incorrect username / password",JOptionPane.ERROR_MESSAGE);
                }else if(isAdmin && attempts >= 5){
                int result = JOptionPane.showConfirmDialog(null, "You have consecutively entered wrong password. Forgot password?", "Incorrect password",JOptionPane.ERROR_MESSAGE);
                if(result == 0){
                   forgotDialog.setVisible(true);
                   questionLabel.setText(question);
                }
            }
            }else if(noQuestionSet){
                JOptionPane.showMessageDialog(null, "Please set your security question.", "Set Security Question",JOptionPane.ERROR_MESSAGE);
                setQuestionDialog.setVisible(true);
            }else{
                Main main = new Main();
                Main.setUser(name);
                Main.setUserName(user);
                UserUI.setUser(user);
                main.setVisible(true);
                userLogIn.setVisible(false);
                attempts = 0;
            }
            loggingIn=false;
        }
        catch ( SQLException err ){
            JOptionPane.showMessageDialog(null, "The username or password you entered is incorrect.", "Incorrect username / password",JOptionPane.ERROR_MESSAGE);
            err.printStackTrace();
        }catch(NullPointerException npe){
            
        }
        
     PrintWriter pw = null;
     try {
     pw = new PrintWriter(new FileOutputStream("remember.txt", false));
     } catch (Exception e){}
     String username = userNameInput.getText();    
     if(rememberMe.isSelected()){
         pw.println(username);
         pw.close();
     }else{
         pw.println("");
         pw.close();
     }
        }
        }
        
    public void checkrememberme(){
        try{
        FileInputStream remember = new FileInputStream("remember.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(remember));
        String strLine;
        strLine = br.readLine();
        if(strLine.isEmpty()){
           userNameInput.requestFocus();
        }else{
           passwordInput.requestFocus();
        }
        }catch(FileNotFoundException fnfe){
            
        }catch(IOException ioe){
            
            
        }
    }
    public void rememberme(){
        try{
        FileInputStream remember = new FileInputStream("remember.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(remember));
        String strLine;
        strLine = br.readLine();
        if(strLine.isEmpty()){
            rememberMe.setSelected(false);
        }else{
            rememberMe.setSelected(true);
        }
        }catch(FileNotFoundException fnfe){
            
        }catch(IOException ioe){
            
        }
        }
    
    public void remember(){
        try {
        if(rememberMe.isSelected()){    
            FileInputStream remember = new FileInputStream("remember.txt");
            BufferedReader br = new BufferedReader(new InputStreamReader(remember));
            String strLine; 
            strLine = br.readLine();
            userNameInput.setText(strLine);
        }else{
//            usernameInput.setText("");
        }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(UserLogIn.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(UserLogIn.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void forgotPassword(){
        try{
            ResultSet rs = dbConnector.query("SELECT username, answer FROM users");
            String quest = questionLabel.getText();
            String ans = answerTextField.getText();
            String username = userNameInput.getText();
            String answer = "";
            String un = "";
            int newpass = (int) (Math.random()*100000);
            boolean correct = false;
            while(rs.next()){
                un = rs.getString(1);
                answer = rs.getString(2);
                if(username.equals(un) && ans.equals(answer)){
                    correct = true;
                    break;
                }else{
                    correct = false;
                }
                }
            if(correct){
                forgotDialog.setVisible(false);
                dbConnector.update("UPDATE users SET password = ? where username = ?", new String []{Integer.toString(newpass), username});
                JOptionPane.showMessageDialog(null, newpass, "New password",JOptionPane.INFORMATION_MESSAGE); 
                attempts = 0;
            }else{
                answerTextField.setText("");
                JOptionPane.showMessageDialog(null, "Your answer is wrong.", "Incorrect username / password",JOptionPane.ERROR_MESSAGE);
            }
        }catch(SQLException e){
            e.printStackTrace();
        }
    }
    
    public void confirmSecurityQuestion(){
        try{
            if(InputValidator.checkInput(ansTextField.getText(), "You must provide an answer to the security question.")){
                String setQuestion = questions.getSelectedItem().toString();
                String ans = ansTextField.getText();
                String[] values = {setQuestion, ans, username};
                dbConnector.update("UPDATE users SET question= ?, answer= ? WHERE username= ?", values);
                JOptionPane.showMessageDialog(null, "Security question has been successfully set.", "Set Security Question",JOptionPane.INFORMATION_MESSAGE);
                setQuestionDialog.setVisible(false);
                Main main = new Main();
                Main.setUser(name);
                Main.setUserName(username);
                main.setVisible(true);
                userLogIn.setVisible(false);
                attempts = 0;
            }
        }catch(SQLException sqle){
            sqle.printStackTrace();
        }
    }
}
